<?php
namespace WenwenPay\Traits;

use WenwenPay\Exception\PaymentException;
use WenwenPay\Exception\InvalidConfigException;
use WenwenPay\Exception\InvalidResponseException;

trait HttpClientTrait
{
    protected function sendRequest(array $params, string $type): array
    {
        // 验证 API URL
        $apiUrl = $this->config->getApiUrl($type);
        if (empty($apiUrl)) {
            throw new InvalidConfigException("Invalid API type: {$type}");
        }

        // 验证必要参数
        if (empty($params['agentNo']) || empty($params['timestamp'])) {
            throw new InvalidConfigException("Missing required parameters");
        }

        $ch = curl_init();
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($params),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json',
                'User-Agent: WenwenPay-PHP-SDK/1.0'
            ],
            // 暂时禁用 SSL 验证
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 10
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            throw new PaymentException("HTTP Request Failed: " . $error);
        }

        if ($httpCode !== 200) {
            throw new PaymentException("Invalid HTTP response code: " . $httpCode);
        }
        
        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidResponseException("Invalid JSON Response", ['response' => $response]);
        }
        
        return $result;
    }
} 